const connection = require('../utils/myconn');
const moment = require('moment')
exports.getAllPost = (obj, callback) => {
    var sql = `SELECT posts.*,users.nickname,categories.name
        FROM posts
        JOIN users on posts.user_id = users.id
        JOIN categories on posts.category_id = categories.id where 1=1  ` // 这里添加一个恒成立条件
        
        if( obj.cate && obj.cate != 'all'){ // 有没有传递分类数据
            sql += ` and posts.category_id = ${obj.cate} `
        }
        if(obj.status && obj.status != 'all'){
            sql += ` and posts.status ='${obj.status}' `
        }

        sql += ` order by id desc
        limit ${(obj.pageNum-1)*obj.pageSize},${obj.pageSize}`;
    connection.query(sql, (err, results) => {
        if (err) {
            callback(err);
        } else {
            // 在创sql语句,进行查询
            sql = `SELECT count(*) as cnt
            FROM posts
            JOIN users on posts.user_id = users.id
            JOIN categories on posts.category_id = categories.id`
            connection.query(sql, (err2, res2) => {
                console.log(sql)
                if (err2) {
                    callback(err2)
                } else {
                    // 不仅仅要返回之前的数据,还要返回当前查询总记录数
                    callback(null, {
                        data: results,
                        total: res2[0].cnt
                    });
                }
            })
        }

    })

}


exports.addPost = (obj,callback)=>{
    // 创建sql语句
    let sql = `insert into posts set ?`
    
    connection.query(sql,obj,(err,result)=>{
        if(err){
                callback(err)
        }else{
                callback(null)
        }
    })
}